<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="./css/common.css"/>
		<link rel="stylesheet" type="text/css" href="../../css/icon.css"/>
		<title>风机检查项</title>
		<style type="text/css">
			.category-list .mui-table-view-cell>a:not(.mui-btn) {
				display: -ms-flexbox;
				display: -webkit-flex;
				display: flex;
				-webkit-align-items: center;
				align-items: center;
				-webkit-justify-content: space-between;
				justify-content: space-between;
			}
			.check-item-label {
				line-height: 16px;
				padding-left: 12px;
				color: #000000;
				border-left: 3px solid #004A86;
			}
			.submit-btn {
				/* position: absolute;
				bottom: 30px;
				left: 0;
				right: 0;
				z-index: 3; */
				width: 80%;
				margin: 30px auto;
				line-height: 50px;
				border-radius: 10px;
				background-color: #004A86;
				color: #FFFFFF;
				text-align: center;
			}
			.category-list .iconfont {
				color: #FA8100;
				margin-right: 20px;
				font-size: 20px;
			}
		</style>
	</head>
	<body>
		<div id="container">
			<header class="mui-bar mui-bar-nav">
				<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
				<h1 class="mui-title">{{ title }}</h1>
			</header>
			<div id="scroll" class="mui-content mui-scroll-wrapper" :style="{height: height + 'px'}">
				<div class="mui-scroll">
					<ul class="mui-table-view category-list">
						<li class="mui-table-view-cell" v-for="(item, index) in checkItemList" :key="item.id" @tap="toCheckDetail(item)">
							<a class="mui-navigate-right flex-center">
								<!-- 单项全部完成，单项未全部完成，已提交，未处理四种状态 -->
								<span class="check-item-label" :class="{'color-green': item.status == 2 || item.status == 3, 'color-pink': item.status == 1}">{{ item.serial_number }}. {{ item.content }}</span>
								<!-- <i class="iconfont icon-complete"></i> -->
							</a>
						</li>
						<!-- <li class="mui-table-view-cell mui-selected">
							<a class="mui-navigate-right"><span class="check-item-label color-pink">2. 控制系统电器测试</span></a>
						</li>
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right"><span class="check-item-label">3. 制动系统</span></a>
						</li>
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right"><span class="check-item-label">4. 主轴</span></a>
						</li> -->
					</ul>
					<div v-show="checkItemList.length" id="submit" class="submit-btn">提 交</div>
				</div>
			</div>
		</div>
		
		<script src="../../js/mui.min.js"></script>
		<script src="../../js/vue.js"></script>
		<script src="../../js/common.js"></script>
		<script src="../../js/mkeyplus.base.js"></script>
		<script src="../../js/storage.js"></script>
		<script src="../../js/uuid.js"></script>
		<script src="./js/uploadImage.js"></script>

		<script type="text/javascript">
			(function($) {
				var cv = null; // 当前webview
				var netStatus = null; // 网络状态
				var categoryVM = null;
				var storageDraftList; // 离线的草稿箱列表
				var blowerId = null; // 当前风机id
				var currentBlower = null; // 当前风机
				var currentItemTemplateList = null; // 当前风机模版数据
				var managerId = ''; // 负责人id
				var groupIds = ''; // 班组人员id
				var type = null; // 0，半年检，1，全年检
				var templateId = null; // 所使用的模板id
				var latestTime = ''; // 最晚定检时间
				var userId = localStorage.getItem('userid'); // 当前登陆的user
				
				$.init();
				
				categoryVM = new Vue({
					el: '#container',
					data: {
						title: '', // 风机号
						height: 0, // 滚动区域高度
						checkItemList: [] // 定检大项列表
					},
					created:function() {
						this.initHeight()
					},
					methods: {
						// 设置高度
						initHeight: function() {
							this.height = window.innerHeight;
						},
						// 
						getCheckItemList: function() {
							// 获取最新数据，对比后缓存
						},
						toCheckDetail: function(item) {
							var that = this;
              
							console.log(item)
							var prop = type === 1 ? 'one_year' : 'half_year';
							// 根据type筛选出全年检或半年检的小项
							var willCheckItem = item.checkinfo.filter(function(ele) {
								return ele[prop] === 1;
							})
							console.log(JSON.stringify(willCheckItem))
							mui.openWindow({
								url: '../regularCheck/checkDetail.html',
								id: '../regularCheck/checkDetail.html',
								extras: {
									sb_name: that.title, // 风机编号
									itemId: item.id, // 大项id
									blowerId: blowerId, // 风机id
									managerId: managerId,
									groupIds: groupIds,
									type: cv.type,
									templateData: JSON.stringify(willCheckItem),
									templateId: templateId,
									latestTime: latestTime
								},
								waiting: {
									autoShow: true
								}
							})
						},
						// 设置状态
						setStatus: function(id, status) {
							console.log('id: ' + id)
							console.log('status: ' + status)
							var index = null;
							for (var i = 0; i < this.checkItemList.length; i++) {
								if (this.checkItemList[i].id == id) {
									index = i;
									break;
								}
							}
							// 查询此风机下大改变的大项,替换checkinfo数据
							storageDraftList = myStorage.getItem('blowerDraftList') || [];
							var curBlower = storageDraftList.filter(function(ele) {
								return ele.userId == userId && ele.id == blowerId;
							})[0];
							var curItem = curBlower.categoryList.filter(function(ele) {
								return ele.id == id;
							})[0];
							this.$set(this.checkItemList[i], 'checkinfo', curItem.checkinfo);
							this.$set(this.checkItemList[i], 'status', status);
						}
					}
				});
				
				$.plusReady(function() {
					cv = plus.webview.currentWebview();
					categoryVM.title = cv.sb_name;
					blowerId = cv.itemId;
					type = cv.type; // 0 半年检 1 一年检
					managerId = cv.managerId; // 负责人id
					groupIds = cv.groupIds; // 班组人员id
					templateId = cv.templateId; // 所使用的模板id
					latestTime = cv.latestTime;
					netStatus = plus.networkinfo.getCurrentType();
					if (cv.templateData) {
						// 由待定检列表进入
						categoryVM.checkItemList = currentItemTemplateList = JSON.parse(cv.templateData);
					} else {
						// 由草稿箱进入，本地获取草稿箱数据
						storageDraftList = myStorage.getItem('blowerDraftList') || [];
						currentBlower = storageDraftList.filter(function(ele) {
							return ele.userId == userId && ele.id === blowerId;
						})[0];
						// 查询对应模版
						var allTemplates = myStorage.getItem('itemTemplate');
						var curTemplate = allTemplates.filter(function(ele) {
							return ele.id == templateId
						})[0];
						var composeTemplate = curTemplate.checkflist.map(function(ele) {
							var cid = ele.id
							var curItem = currentBlower.categoryList.filter(function(item) {
								return item.id == cid
							});
							if (curItem.length) {
								curItem[0].serial_number = ele.serial_number;
								curItem[0].content = ele.content;
								return curItem[0];
							} else {
								return ele;
							}
						});
						categoryVM.checkItemList = composeTemplate;
					}
					$('#scroll').scroll({
						indicators: true //是否显示滚动条
					});
				});
				
				// 调整草稿箱中大项状态status
				function updateSubmitStatus(itemIds) {
					var storageDraftList = myStorage.getItem('blowerDraftList') || [];
					var curBlower = storageDraftList.filter(function(ele) {
						return ele.userId == userId && ele.id == blowerId;
					})[0];
					var curItems = curBlower.categoryList.filter(function(ele) {
						return itemIds.indexOf(ele.id) > -1;
					});
					$.each(curItems, function(i, ele) {
						ele.status = 3;
					});
					myStorage.setItem('blowerDraftList', storageDraftList);
				}
				
				// 提交
				function handleSubmit(options, cb) {
					var userId = localStorage.getItem('userid');
					var list = options.map(function(ele) {
						/* if (ele.is_photograph && !ele.uploadImagePath) {
							$.toast(ele.serial_number + ' 项图片上传失败，请稍后重新提交')
						} */
						return {
							id: ele.id,
							data_record: ele.data_record || '',
							desc: ele.remarks || '',
							image: ele.uploadImagePath || '',
							check_user: userId,
							status: ele.status,
							actual_value:ele.actual,
              actual_unit:ele.actual_unit
						}
					})
					var params = {
						id: blowerId,
						checkInfo: JSON.stringify(list),
						job_manager:managerId,
						group_user: groupIds
					}
					var wt = plus.nativeUI.showWaiting('正在提交...');
					$.baseApp.httpRequst('/api/v2/inspection/submitCheckPointInfo', params,
						function(res) {
							wt.close();
							console.log("提交定检设备：" + JSON.stringify(res));
							if (res.status === 200) {
								$.toast(res.message, { type: 'div' });
								$.later(function(){
									if (cb && typeof cb === 'function') {
										cb();
									}
								}, 1000);
							} else {
								$.toast(res.message, { type: 'div' })
							}
						},
						function(err) {
							wt.close();
							console.log(err)
						},
						'post'
					);
				}
				// 提交验证
				document.getElementById('submit').addEventListener('tap', function() {
					netStatus = plus.networkinfo.getCurrentType();
					if (netStatus > 1) {
						// 1、清除离线存储中的当前提交项 2、通知opener更新草稿箱数据及定检记录数据
						console.log(categoryVM.checkItemList);
						var allData = categoryVM.checkItemList;
						var pass = true; // 通过验证
						for (var i = 0; i < allData.length; i++) {
							var item = allData[i]
              
							if (item.status && item.status == 1) {
                
								var msg = '第' + item.serial_number + '中您还有检查项未填写数据，请检查后提交'
								$.toast(msg, { type: 'div' });
								pass = false;
                console.log(item.serial_number);
								break;
							}
						}
						if (!pass) return;
						var submitCategoryIds = []; // 要提交的大项id数组
						var willSubmitItems = allData.filter(function(ele) {
							if (ele.status == 2 || ele.status == 3) {
								submitCategoryIds.push(ele.id);
							}
							return ele.status == 2 || ele.status == 3;
						}).map(function(ele) {
							return ele.checkinfo;
						});
						var willSubmitData = [];
						$.each(willSubmitItems, function(i, ele) {
							willSubmitData = willSubmitData.concat(ele)
						});
						if (!willSubmitData.length) {
							$.toast('您没有要提交的检查项数据', { type: 'div' })
							return;
						}
						// 处理待提交数据中的图片
						var maxIndex = 0; // 有图片的项的索引
						$.each(willSubmitData, function(i, ele) {
							if (ele.images && ele.images.length) {
								maxIndex = i;
							}
						})
						if (maxIndex === 0) {// 直接提交
							handleSubmit(willSubmitData, function() {
								updateSubmitStatus(submitCategoryIds); // 提交之后更新已提交的大项status 3
								var opener = cv.opener();
								$.fire(opener, 'updateDraftAndRecord');
								cv.close();
							});
						} else {// 上传图片后提交
							$.each(willSubmitData, function(i, ele) {
								if (ele.images && ele.images.length) {
									(function(item, n) {
										// 每一小项只能有一张图片
										upload(item.images[0], function(savePath) {
											console.log(savePath)
											item.uploadImagePath = savePath
											if (n === maxIndex) { // 上传至最大索引项，开始提交
												handleSubmit(willSubmitData, function() {
													updateSubmitStatus(submitCategoryIds); // 提交之后更新已提交的大项status 3
													var opener = cv.opener();
													$.fire(opener, 'updateDraftAndRecord');
													cv.close();
												});
											}
										});
									})(ele, i);
								}
							});
						}
					} else {
						$.toast('请在网络连接良好时提交数据', { type: 'div' });
					}
				});
				// 刷新列表状态
				window.addEventListener('refreshList', function(event){
				  var id = event.detail.id;
				  var status = event.detail.status;
				  categoryVM.setStatus(id, status);
				});
			})(mui);
		</script>
	</body>
</html>
